import { AfterViewInit, Input, ViewChild } from '@angular/core';
import { DxDataGridComponent } from 'devextreme-angular/ui/data-grid';
import { QueryView } from './query-view';


export class QueryModalView<U, B, S> extends QueryView<U, B, S> implements AfterViewInit {
  @Input() selectionMode = 'single';
  @Input() allowSelectAll = false;
  @Input() maxSelectCount = 100;
  @Input() queryParams: any = {};
  @Input() type: string;
  @ViewChild(DxDataGridComponent, { static: true }) dataGrid: DxDataGridComponent;

  saveSelectedRows = [];
  /** 表格多选比较的属性，可重写 */
  dataGridCompareWithKey = 'id';

  get result() {
    return this.saveSelectedRows;
  }

  private skipSelectionChanged = false;
  private __ngAfterViewInit = false;

  constructor() {
    super();

    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        if (!this.__ngAfterViewInit) {
          this.loggerService.error(new Error('"super.ngAfterViewInit()" Not Implemented ---> ' + this.constructor.name));
        }
      }, 3000);
    });
  }
  // 重写重绘表格方法为空
  subscribeAsideCollapsed() {
  }
  ngAfterViewInit(): void {
    this.__ngAfterViewInit = true;
    super.ngAfterViewInit();
    this.dataGrid.instance.option('height', '435px');
    this.dataGrid.instance.option('selection.mode', this.selectionMode);
    this.dataGrid.instance.option('cacheEnabled', false);
    this.dataGrid.instance.option('selection.allowSelectAll', this.allowSelectAll);
    const wrapper = (<any>this.dataGrid.instance)._$element[0];
    if (!this.allowSelectAll && wrapper) {
      wrapper.classList.add('no-select-all');
    }

    this.dataGrid.onSelectionChanged.subscribe((e) => {
      this.selectionChangedHandler(e);
    });
    this.dataGrid.pager.visible = true;
  }

  /** 表格多选比较的方法，可重写 */
  dataGridCompareWithFn(selectedItem: any, row: any) {
    return selectedItem[this.dataGridCompareWithKey] === row[this.dataGridCompareWithKey];
  }

  /** dataGrid数据行被选中或者取消选中的回掉 */
  protected selectionChangedHandler($event) {
    if (this.skipSelectionChanged) {
      return;
    } else if ($event.currentSelectedRowKeys.length > 0 && this.saveSelectedRows.length >= this.maxSelectCount) {
      this.dataGrid.instance.deselectRows($event.currentSelectedRowKeys);
      return;
    }

    const deselected = $event.currentDeselectedRowKeys;
    const selected = $event.currentSelectedRowKeys;

    for (let i = 0; i < deselected.length; i++) {
      const row = deselected[i];
      const findRowIndex = this.saveSelectedRows.findIndex((item) => this.dataGridCompareWithFn(item, row));
      if (findRowIndex !== -1) {
        this.saveSelectedRows.splice(findRowIndex, 1);
      }
    }

    for (let i = 0; i < selected.length; i++) {
      const row = selected[i];
      const findRowIndex = this.saveSelectedRows.findIndex((item) => this.dataGridCompareWithFn(item, row));
      if (findRowIndex === -1) {
        if (this.selectionMode === 'multiple') {
          this.saveSelectedRows.push(row);
        } else if (this.selectionMode === 'single') {
          this.saveSelectedRows = [row];
        } else {
          this.saveSelectedRows = [];
        }
      }
    }
  }

  /** 移除已经选择的数据项 */
  removeSaveSelected(item: any) {
    const index = this.saveSelectedRows.findIndex((selected) => {
      return selected[this.dataGridCompareWithKey] === item[this.dataGridCompareWithKey];
    });
    this.saveSelectedRows.splice(index, 1);
    const selectedRows = this.dataGrid.instance.getSelectedRowKeys();
    const deselectRows = [];
    for (let i = 0; i < selectedRows.length; i++) {
      const row = selectedRows[i];
      if (row[this.dataGridCompareWithKey] === item[this.dataGridCompareWithKey]) {
        deselectRows.push(row);
      }
    }
    this.dataGrid.instance.deselectRows(deselectRows);
  }

  /** dataGrid数据行刷新时重新根据新的数据行判断是否需要选中 */
  protected postLoad(res: any) {
    this.skipSelectionChanged = true;
    const selectedRowsIndex = [];
    res.data.forEach((item, index) => {
      for (let i = 0; i < this.saveSelectedRows.length; i++) {
        const row = this.saveSelectedRows[i];
        if (row[this.dataGridCompareWithKey] === item[this.dataGridCompareWithKey]) {
          selectedRowsIndex.push(index);
          break;
        }
      }
    });

    setTimeout(() => {
      this.dataGrid.instance.selectRowsByIndexes(selectedRowsIndex).then((e) => {
        this.skipSelectionChanged = false;
      });
    }, 0);

  }
}
